import qs from 'query-string';
import request from 'superagent';
import { host, node_env } from '../config';

const urlPrefix = `http://${host}/api/v1/data`;
const isDebugging = node_env === 'development';

function filterText(res) {
  const textJson = JSON.parse(res.text);
  return textJson;
}

function filterStatus(res) {
  if (res.status >= 200 && res.status < 300) {
    return res;
  }

  const error = new Error(res.statusText);
  error.res = res;
  error.type = 'http';
  throw error;
}

export async function get(url, params) {
  url = urlPrefix + url;

  if (params) {
    url += `?${qs.stringify(params)}`;
  }

  if (isDebugging) {
    console.info('GET: ', url);
    console.info('Params: ', params);
  }

  const res = await request.get(url);
  const result = filterStatus(res);
  return filterText(result);
}

export async function post(url, body = {}) {
  url = urlPrefix + url;

  let csrf = '';

  if (typeof window !== 'undefined') {
    csrf = document.getElementsByTagName('meta')['csrf-token'].getAttribute('content');
  }

  body = { ...body, _csrf: csrf };

  if (isDebugging) {
    console.info('POST: ', url);
    console.info('Body: ', body);
  }

  const res = await request.post(url)
    .send(body)
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .withCredentials();

  const result = filterStatus(res);
  return filterText(result);
}

